import pymssql
import time
import configparser 

#------db config---------
db_host = ""
db_user = ""
db_passwd = ""
db_database = ""
db_charset = ""
#-----db table config----
tableName = ""  # split by '#',example: tableA#tableB#tableC
#-----server config------
server_host = ""

def readConfig(): 
	global db_host
	global db_user
	global db_passwd
	global db_database
	global db_charset
	#-----db table config----
	global tableName  # split by '#',example: tableA#tableB#tableC
	#-----server config------
	global server_host
	cf = configparser.ConfigParser()
	cf.read("param.conf")
	db_host = cf.get("db", "db_host").strip()
	db_user = cf.get("db", "db_user").strip()
	db_passwd = cf.get("db", "db_passwd").strip()
	db_database = cf.get("db", "db_database").strip()
	db_charset = cf.get("db", "db_charset").strip()

	tableName = cf.get("tables", "tableName").strip()

	server_host = cf.get("server", "server_host").strip()

	print("*-----read param config success-----------")
	print("*    db_host     :"+db_host)
	print("*    db_user     :"+db_user)
	print("*    db_passwd   :"+db_passwd)
	print("*    db_database :"+db_database)
	print("*    db_charset  :"+db_charset)
	print("*    tableName   :"+tableName)
	print("*    server_host :"+server_host)
	print("*-----------------------------------------")

# 创建数据库连接
def createConnection():
	try:
		conn = pymssql.connect(server=db_host, user=db_user, password=db_passwd, database=db_database,charset=db_charset)
	except BaseException:
		print("获取数据库连接失败！")
		exit(-1)
	if(conn):
		print("获取数据库连接成功！")
		print("*-----------------------------------------\n\n")
	return conn

#关闭数据库连接。
def closeConnection(conn):
	conn.close()

# 查询数据
def query(conn,table):
	#print("开始查询数据")
	cursor = conn.cursor()
	cursor.execute("select * from "+table)
	resList = cursor.fetchall()
	if(resList):
		delete(conn,table)
	return resList

def delete(conn,table):
	#print("开始删除数据")
	cursor = conn.cursor()
	cursor.execute("delete from "+table)
	conn.commit()
	#print("删除数据成功")
	#
def dealRes(p,table):
	if(p==[]):
		return
	list2=[str(i).replace(" ","") for i in p]
	list3=','.join(list2)
	print("捕获到更新数据：\n"+list3)

def sendData(table,data):
	test_data = {'tableName':table,'data':data}
	test_data_urlencode = urllib.urlencode(test_data)
	req = urllib2.Request(url = server_host,data =test_data_urlencode)

def getParam():
	cf = ConfigParser.ConfigParser()

def selectData(conn):
	tables = tableName.split("#")
	for table in tables:
		reslist = query(conn,table)
		dealRes(reslist,table)

def main():
	readConfig()
	conn = createConnection()
	while True:
		selectData(conn)
		time.sleep(5)

if __name__ == '__main__':
	main()